<?php
ob_start();
session_start();
/*echo '<pre>';
print_r($_POST); exit;*/
include("../includes/db_conn_new.inc");
include("requestmoneyformfileds.php");

if ($finalstatusByDecision=='pass')
	$app_result='Pre-Approved';
else
	$app_result='Declined';

	if($title=='Ms'||$title=='Miss'||$title=='Mrs')
		$gender='female';
	else if($title=='Mr'||$title=='Dr'||$title=='Other')
		$gender='male';
	else
		$gender='';
		
	if($residenceperiod=='1 month')
	{
		 $residenceperiod='Month/s';
		 $residencelength='1';
	}
	else if($residenceperiod=='2 months')
	{
		 $residenceperiod='Month/s';
		 $residencelength='2';
	}
	else if($residenceperiod=='3 months')
	{
		 $residenceperiod='Month/s';
		 $residencelength='3';
	}
	else if($residenceperiod=='less than 1 month')
	{
		 $residenceperiod='Month/s';
		 $residencelength='less than 1';
	}
	else if($residenceperiod=='4 to 6 months')
	{
		 $residenceperiod='Month/s';
		 $residencelength='4 to 6';
	}
	else if($residenceperiod=='7 months to 1 year')
	{
		 $residenceperiod='Month/s';
		 $residencelength='7 to 12';
	}
	else if($residenceperiod=='1 year to 2 years')
	{
		 $residenceperiod='Year/s';
		 $residencelength='1 to 2';
	}
	else if($residenceperiod=='more than 2 years')
	{
		 $residenceperiod='Year/s';
		 $residencelength='more than 2';
	}
	
	$street = $street.','.$streettype;
	
 
 
 
 $app_insert_qry = "INSERT INTO crm_application (deletedFlag,
												 app_result, 
												 Loan_No,
												 Folder,
												 NoInApplication,
												 OfferedAmount,
												 DesiredAmount,
												 amountMoto,
												amoutProperties,
												TextAwaitDoc,
												PurposeSummary,
												Memo,LenderID,
												OutSrcLenderVal,
												ReferrerID,
												ReferrerVal,
												CreatedDate,
												EditDate,
												comesfrom,
												securities,
												IsUSB,
												IsCarOwner,
												status,
												MC_process,
												CreatedTime,
												mc_preferred_loan_period,
												mc_ipaddress,
												mc_income_status,
												mc_asset_status,
												mc_credit_status,
												mc_final_status,
												mc_ClientUpdateTime,
												mc_purposeType,
												mc_OtherPurpose,
												mc_Update_Time,
												mc_agreement,
												mc_browser,
												mc_referrer_company,
												mc_referrer_email,
												loanpurposereason,
												`filledout`,
												`prevclient`,
												`purposedetail`,
												`boardingfee`,
												`livingfee`,
												`totalincome`,
												`totalexpense`,
												`totalexpensecorrect`,
												`disposableincome`,
												`ELA`,
												`formviewnotice`,
												`whyus`,
												`timecost`,
												`preappcode`)
 										values('0',
											   '".$app_result."',
											   '',
											   '',
											   '1',
											   '".$loanamount."',
											   '".$loanamount."',
											   '',
											   '',
											   'None doc',
											   'SACC',
											   '',
											   '0',
											   '',
											   '0',
											   '',
											   NOW(),
											   NOW(),
											   'MaxCash',
											   '',
											   'No',
											   '0',
											   'opening',
											   'Waitingverify',
											   CURTIME(),
											   '".$term."',
											   '".$mc_ipaddress."',
											   '',
											   '',
											   '',
											   '".$finalstatusByDecision."',
											   CURTIME(),
											   '',
											   '".$mc_OtherPurpose."',
											   NOW(),
											   '".$mc_agreement."',
											   '".$mc_browser."',
											   '',
											   '',
											   '".$purposeofloan."',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '',
											   '')";
	
	if(!$sql1 = mysql_query($app_insert_qry))  
		echo mysql_error();
		
	$app_id=mysql_insert_id();
	$_SESSION['app_id'] = $app_id;
  
 $sql2=mysql_query("UPDATE `crm_contact` SET `FirstName` = '".$firstname."',`MiddleName` = '".$middlename."',`SurName` = '".$surname."',
`Mobile` = '".$mobile."',`HomePhone` = '".$phone."',`Email` = '".$emailaddress."',
`DriverLicense` = '',`DateBirth` = STR_TO_DATE('".$dateofbirth."', '%d/%m/%Y'),
`StreetNo` = '".$streetnumber."',`Street` = '".$street."',`Suburb` = '".$suburb."',`State` = '".$state."',`PostCode` = '".$postcode."',`ResidencePeriod` = '".$residenceperiod."',`ResidenceLength` = '".$residencelength."',`Dependant` = '".$numberofdependant."',`app_ResidentialStatus` = '".$residentialstatus."',`app_number` = NULL,`app_id` = ".$app_id.",
`NumberFromAppinfo` = NULL,`Memo` = '',`EditDate` = NOW(),`DupwithContact` = NULL,`deletedFlag` = '0',`Role` = '',
`Relationship` = '',`WorkPhone` = '',`FaxNumber` = '',`secondEmailAddress` = '',`PostalAddress` = '',
`IncomeType` = '',`SelfEmpTypeofEntity` = '',`SelfEmpBusinessName` = '',`SelfEmpABN` = '',`SelfEmpNatureofBusiness` = '',
`SelfEmpPhone` = '',`SelfEmpAddress` = '',`KinsName` = '',`KinsRelationship` = '',`KinsContactNumber` = '',`Notes` = '',
`EmpEmployer` = '',`EmpOccupation` = '',`EmpJobPosition` = '',`EmpEmployerPhone` = '',`EmpContactPerson` = '',
`EmpWorkAddress` = '',`comesfrom` = 'MaxCash',`Unsubscribe_Ad` = '0',`Sacc_accountlock` = '0'
WHERE ContactID='".$_SESSION['applicant_id']."'");
 

$sql3=mysql_query("INSERT INTO `crm_applicationcontact`
(`app_id`,`ContactID`,`NoInApplication`,`CombineApp`,`deletedFlag`)
VALUES(".$app_id.",'".$_SESSION['applicant_id']."','1','','0')");

$loginid=0;$sql20="select loginid from client_logininfo where CurrentContact_id=".$_SESSION['applicant_id']." order by loginid desc limit 0,1";                
$res = mysql_query($sql20);
$num_rows = mysql_num_rows($res);
if($num_rows > 0)
{
	while($row = mysql_fetch_array($res))
	{
		$loginid= $row['loginid'];                                  
	}
} 

$sql14=mysql_query("UPDATE client_logininfo SET CurrentContact_id=".$_SESSION['applicant_id'].",OriginalContact_id=".$_SESSION['applicant_id'].",display_name='".$firstname."',email_address='".$emailaddress."',v_email='0',status='1',CreatedDate=NOW(),EditDate=NOW(),Comesfrom='MaxCash' where loginid='".$loginid."'");

 $sql4=mysql_query("UPDATE crm_employment SET app_id=".$app_id.",employment_type='".$typeofemployment."',employment_occupation='".$titleinoccupation."',employer_name='".$businessname."',employer_phone='".$workphone."',EditDate=NOW() where OriginalContact_id='".$_SESSION['applicant_id']."'");

 $sql5=mysql_query("UPDATE crm_income SET app_id=".$app_id.",income_aftertax='".$incomeaftertax."',income_aftertax_period='".$incomeaftertax1period."',income_centrelink='".$CentrelinkIncome1."',income_other='".$OtherIncomeSpecify1."',income_other_period='".$OtherIncomePeriod1."',income_rental='".$RentalIncome1."',EditDate=NOW() where OriginalContact_id='".$_SESSION['applicant_id']."'");

 $sql6=mysql_query("UPDATE crm_applicationcredit SET app_id=".$app_id.",credit_hardship='".$hardship."',credit_gambling='".$Gambling."',credit_claims='".$loaninlasttwomonth."',credit_history='".$credithistory."',credit_outstanding='".$totaloutstanding."',credit_dischargedate='".$dateofdischarge."',credit_discharge='".$defaultafterdischarge."',WhyChooseMF='".$whychoosemf."',
	ExistingClient='".$existingclient."',EditDate=NOW() where OriginalContact_id='".$_SESSION['applicant_id']."'");

$sql7=mysql_query("UPDATE `crm_liabilities` SET app_id=".$app_id.",`liabilities_loanrepayment_payment`='".$liabilitiesloanrepaymentpayment."',`liabilities_loanrepayment_paymentperiod`='".$loanrepaymentperiod."',`liabilities_creditcard_payment`='".$liabilitiescreditcardpayment."',`liabilities_creditcard_paymentperiod`='".$creditcardpaymentperiod."',`liabilities_boardingrentingfee_payment`='".$liabilitiesboardingrentingfeepayment."',`liabilities_boardingrentingfee_paymentperiod`='".$boardingrentingperiod."',`liabilities_livingexpenses_payment`='".$liabilitieslivingexpensespayment."',`liabilities_livingexpenses_paymentperiod`='".$livingexpensesperiod."',`EditDate`=NOW() where OriginalContact_id='".$_SESSION['applicant_id']."'");

$sql12=mysql_query("INSERT INTO `form_mc`
(`deletedFlag`,`OfferedAmount`,`DesiredAmount`,`PurposeSummary`,`LenderID`,`OutSrcLenderVal`,`ReferrerID`,`ReferrerVal`,`status`,`MC_process`,`mc_preferred_loan_period`,`mc_ipaddress`,`mc_income_status`,`mc_asset_status`,`mc_credit_status`,`mc_final_status`,`mc_ClientUpdateTime`,`mc_purposeType`,`mc_OtherPurpose`,`mc_Update_Time`,`mc_agreement`,`mc_browser`,`mc_referrer_company`,`mc_referrer_email`,`FirstName`,`MiddleName`,`SurName`,`Title`,`Gender`,`Mobile`,`HomePhone`,`Email`,`DriverLicense`,`Citizenship`,`DateBirth`,`StreetNo`,`Street`,`Suburb`,`State`,`PostCode`,`ResidencePeriod`,`ResidenceLength`,`Dependant`,`app_ResidentialStatus`,`WorkPhone`,`FaxNumber`,`Email1`,`secondEmailAddress`,`PostalAddress`,`boardingwith_name`,
`Application_Memo`,`Contact_Memo`,`viewtemplatepath`,`CreatedDate`,`EditDate`,`credit_hardship`,`credit_gambling`,`credit_claims`,`credit_history`,
`credit_outstanding`,`credit_dischargedate`,`credit_discharge`,`employment_status`,`employment_type`,`employment_occupation`,`employer_name`,
`employer_phone`,`income_aftertax`,`income_aftertax_period`,`income_centrelink`,`income_other`,`income_other_period`,`income_rental`,`income_total`,`OtherIncomeSpecify`,`liabilities_type`,`liabilities_owing`,`liabilities_loanrepayment_payment`,`liabilities_loanrepayment_paymentperiod`,
`liabilities_creditcard_payment`,`liabilities_creditcard_paymentperiod`,`liabilities_boardingrentingfee_payment`,`liabilities_boardingrentingfee_paymentperiod`,`liabilities_livingexpenses_payment`,`liabilities_livingexpenses_paymentperiod`,`liabilities_bank`)
VALUES
('0','".$loanamount."','".$loanamount."','SACC','0','','0','','opening','Waitingverify','".$term."','".$mc_ipaddress."','','','','".$finalstatusByDecision."',CURTIME(),'','".$mc_OtherPurpose."',NOW(),'".$mc_agreement."','".$mc_browser."','','','".$firstname."','".$middlename."','".$surname."','".$title."','".$gender."','".$mobile."','".$phone."','".$emailaddress."','','".$citizenship."',STR_TO_DATE('".$dateofbirth."', '%d/%m/%Y'),'".$streetnumber."','".$street."','".$suburb."','".$state."','".$postcode."','".$residenceperiod."','".$residencelength."','".$numberofdependant."','".$residentialstatus."','','','','','','','','','',NOW(),NOW(),'".$hardship."','".$Gambling.".',
'".$loaninlasttwomonth."','".$credithistory."','".$totaloutstanding."','".$dateofdischarge."','".$defaultafterdischarge."','','".$typeofemployment."','".$titleinoccupation."','".$businessname."','".$workphone."','".$incomeaftertax."','".$incomeaftertax1period."',NULL,NULL,'','','0','','','','".$liabilitiesloanrepaymentpayment."','".$loanrepaymentperiod."','".$liabilitiescreditcardpayment."','".$creditcardpaymentperiod."','".$liabilitiesboardingrentingfeepayment."','".$boardingrentingperiod."','".$liabilitieslivingexpensespayment."','".$livingexpensesperiod."','')");

$form_id=mysql_insert_id();

$sql13=mysql_query("INSERT INTO `crm_applicationappform`
(`ApplicationId`,`AppFormId`,`ComesFrom`)
VALUES('".$app_id."','".$form_id."','MaxCash')");
mysql_query($sql13);
			
if ($finalstatusByDecision=='pass')
{
	$sql8=mysql_query("INSERT INTO `sacc_verificationstatus`
(`app_id`,`sms_attempts`,`sms_status`,`idcheck_attempts`,`idcheck_status`,`bankretrieve_attempts`,`bankretrieve_status`,`payslip_status`,`CreatedDate`,`UpdatedDate`,`MC_apply`,`creditehistory`,`incomeexpense`,`phoneverification`,`contractprepared`,`contractsigned`,`fundtransferred`)VALUES('".$app_id."','1','0','1','0','1','0','0',NOW(),NOW(),'','0','0','0','0','0','0')");
               
		if ($sql1 and $sql3 and $sql4 and $sql6 and $sql7 and  $sql13 and $sql14) {
    		
                    mysql_query("COMMIT");
			
			echo header('Location: index.php?dashboard');
			exit;
		} else {        	
    		mysql_query("ROLLBACK");
			
		}
	
}
else
{
		if ($sql1 and $sql3 and $sql4  and $sql6 and $sql7 and  $sql13 and $sql14) {
    		mysql_query("COMMIT");
			
			echo header('Location: index.php?dashboard');
		} else {        	
    		mysql_query("ROLLBACK");
			
		}
}
ob_flush();
?>